package org.jeecg.modules.operations.assistant.wechat.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.operations.assistant.vehicle.util.ApiServiceUtil;
import org.jeecg.modules.operations.assistant.wechat.entity.WXPayOrderReqVO;
import org.jeecg.modules.operations.assistant.wechat.entity.WxPayRespVO;
import org.jeecg.modules.operations.assistant.wechat.service.IWeChatPayService;
import org.jeecg.modules.operations.assistant.work.entity.CustomerInfo;
import org.jeecg.modules.operations.assistant.work.service.ICustomerInfoService;
import org.jeecg.modules.operations.assistant.xcbd.entity.XcbdSalesContract;
import org.jeecg.modules.operations.assistant.xcbd.service.IXcbdSalesContractService;
import org.jeecg.modules.system.controller.CommonController;
import org.jeecg.modules.system.entity.SysThirdAccount;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.ThirdLoginModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysThirdAccountService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @Description: 微信登录
* @Author: jeecg-boot
* @Date:   2024-06-06
* @Version: V1.0
*/
@Api(tags="微信支付")
@RestController
@RequestMapping("/wxpay")
@Slf4j
public class WeChatPayController extends JeecgController<CustomerInfo, ICustomerInfoService> {
   @Autowired
   private ICustomerInfoService customerInfoService;
    @Autowired
    private IXcbdSalesContractService xcbdSalesContractService;

    @Value("${justauth.type.WECHAT_MINI_PROGRAM.client-id:}")
    private String weChatClientId;
    @Value("${justauth.type.WECHAT_MINI_PROGRAM.client-secret:}")
    private String weChatClientSecret;
    @Autowired
    private ISysThirdAccountService sysThirdAccountService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDictService sysDictService;

    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private IWeChatPayService wxPayService;

    @Resource
    CommonController commonController;

    @Autowired
    private RestTemplate restTemplate;


 /**
  * 获取手机号接口
  *
  * @return
  */
 @ApiOperation("获取手机号接口")
 @GetMapping("/pay")
 public void pay(String code, String state, HttpServletResponse response) throws IOException {
    log.info("获取微信响应的参数code:{}，state：{}，orderId：{}",code,state);
    // 1、获取 登陆凭证code
    if (StringUtils.isEmpty(code)) {
  //            return result.error("code获取失败！");
  //            return "code获取失败！";
    }

  //        String code = jsonObject.getString("code");
  //        weChatClientId+"&secret="+weChatClientSecret
    String appId = "wx23bf3224159631e6";
    String appSecret = "307083070d24b3fb7fffd7399bdfad25"; // 小程序密钥
  //        if (StringUtils.isEmpty(code)) {
  //            return AjaxResult.error("手机号获取凭证不能为空！");
  //        }
    String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, appSecret,code);
    log.info("url==={}",url);
    JSONObject data = JSON.parseObject(HttpUtil.get(url));
    log.info("data==={}",data);
    // 重定向到另一个路径或者外部URL
    String redirectUrl = "/wechatpay/index.html?openId="+data.getString("openid")+"&orderId="+state+"#/pages/wechatpay/wechatpay";
    response.sendRedirect(redirectUrl);
 }

    @ApiOperation(value = "微信预支付", notes = "微信预支付")
    @PostMapping("/createOrder")
    public Result<WxPayRespVO> createOrder(@RequestBody @Validated WXPayOrderReqVO req) throws Exception {

        return Result.ok(wxPayService.createOrder(req));
    }

    @ApiOperation(value = "微信支付回调", notes = "微信支付回调")
    @PostMapping("/payNotify")
    public Result payNotify(HttpServletRequest request){
        log.info("payNotify1");
        wxPayService.payNotify(request);//注意：回调接口需要暴露到公网上，且要放开token验证
        log.info("payNotify2");
        return Result.ok();
    }
    @ApiOperation(value = "获取订单信息", notes = "获取订单信息")
    @PostMapping("/getOrderInfo")
    public Result<XcbdSalesContract> getOrderInfo(@RequestBody @Validated WXPayOrderReqVO req) throws Exception {
        return Result.ok(xcbdSalesContractService.getSalesContractInfo(req.getOrderSn()));
    }
}